package dao;

import entity.Card;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class CardDao extends BaseDao {

    /**
     *
     * @param startIndex  起始索引
     * @param pageSize 页面大小
     * @return
     */
    public List<Card> list(int startIndex, int pageSize){
        ArrayList<Card> list = new ArrayList<>();

        // JDBC 使用方法
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            //获取连接
            conn = super.getConnection();

            //3. sql
            String sql = "SELECT id,userName,idNumber,`status`,createDate from card ORDER BY createDate DESC  LIMIT ?,?";
            //4. 获取执行对象
            pstmt = conn.prepareStatement(sql);

            //5. 设置参数
            pstmt.setInt(1,startIndex);
            pstmt.setInt(2,pageSize);

            //6. 执行命令
            rs = pstmt.executeQuery();

            //7. 处理结果
            while (rs.next()){
                Card card = new Card();
                card.setId(rs.getInt("id"));
                card.setUserName(rs.getString("userName"));
                card.setIdNumber(rs.getString("idNumber"));
                card.setCreateDate(rs.getString("createDate"));
                card.setStatus(rs.getInt("status"));
                list.add(card);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //8. 释放资源
            super.closeAll(conn,pstmt,rs);
        }
        return list;
    }


    public static void main(String[] args) {
        CardDao cardDao = new CardDao();
        List<Card> list = cardDao.list(0,1);
        for (Card card : list){
            System.out.println(card.getUserName());
        }
    }

}
